<template>
  <div class="page-content exhibition-edit">
    <div class="mb-6 flex justify-between items-center">
      <div>
        <h1 class="text-2xl font-bold">{{ isEdit ? '编辑展品' : '添加展品' }}</h1>
        <p class="text-gray-500 mt-2">{{ isEdit ? '修改展品信息和资料' : '创建新的展品资料' }}</p>
      </div>
      <el-button @click="goBack">
        <el-icon><Back /></el-icon>返回
      </el-button>
    </div>

    <el-card shadow="hover">
      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-position="top"
        status-icon
        require-asterisk-position="right"
        scroll-to-error
      >
        <el-row :gutter="20">
          <!-- 基本信息 -->
          <el-col :span="24">
            <div class="form-section-title mb-4">
              <h2 class="text-lg font-medium">基本信息</h2>
            </div>
          </el-col>

          <el-col :lg="8" :md="12" :sm="24">
            <el-form-item label="展品名称" prop="name">
              <el-input v-model="formData.name" placeholder="请输入展品名称" />
            </el-form-item>
          </el-col>

          <el-col :lg="8" :md="12" :sm="24">
            <el-form-item label="展出状态" prop="status">
              <el-select v-model="formData.status" placeholder="请选择展出状态" class="w-full">
                <el-option
                  v-for="item in exhibitionStatus"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :lg="8" :md="12" :sm="24">
            <el-form-item label="展品定位" prop="location">
              <div class="flex items-center w-full">
                <div class="flex-1">
                  <el-input v-model="formData.location" placeholder="请输入展品定位" />
                </div>
                <el-button class="ml-2" @click="openMapSelection">
                  <el-icon><Location /></el-icon>
                </el-button>
              </div>
             
            </el-form-item>
          </el-col>

          <el-col :lg="8" :md="12" :sm="24">
            <el-form-item label="展出楼层" prop="floor">
              <el-input v-model="formData.floor" placeholder="请输入展出楼层，如：F1、B1" />
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <!-- :maxlength="800" -->
            <el-form-item label="展品介绍" prop="description">
              <el-input
                v-model="formData.description"
                type="textarea"
                :rows="4"
                placeholder="请输入展品详细介绍"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <!-- :maxlength="800" -->
            <el-form-item label="展品介绍（英文）" prop="descriptionEn">
              <el-input
                v-model="formData.descriptionEn"
                type="textarea"
                :rows="4"
                placeholder="请输入展品详细介绍（英文）"
              />
            </el-form-item>
          </el-col>
          <!-- 图片管理 -->
          <el-col :span="24" class="mt-4">
            <div class="form-section-title mb-4">
              <h2 class="text-lg font-medium">图片管理</h2>
            </div>
          </el-col>

          <el-col :span="24">
            <el-form-item label="封面图片" prop="coverImage">
              <div class="w-full">
                <MyUpload
                  :file-list="coverImageList"
                  :limit="1"
                  @deleteFile="coverDeleteFile"
                  @uploadFileSuccess="coverSuccess"
                />
              </div>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="详情图片" prop="detailImages">
              <div class="w-full">
                <MyUpload
                  :file-list="detailImageList"
                  @deleteFile="detailDeleteFile"
                  @uploadFileSuccess="detailSuccess"
                />
              </div>
            </el-form-item>
          </el-col>

          <!-- 语音讲解 -->
          <el-col :span="24" class="mt-4">
            <div class="form-section-title mb-4">
              <h2 class="text-lg font-medium">语音讲解</h2>
            </div>
          </el-col>

          <el-col :span="24">
            <el-form-item label="讲解音频" prop="audioGuide">
              <div class="w-full">
                <MyUpload
                  :file-list="audioList"
                  :limit="1"
                  accept=".mp3"
                  @deleteFile="audioDeleteFile"
                  @uploadFileSuccess="audioSuccess"
                />
                <div v-if="audioList.length > 0" class="mt-2 w-[400px]">
                  <audio
                    v-for="(file, idx) in audioList"
                    :key="file.path || idx"
                    :src="file.path"
                    controls
                    class="w-full"
                  >
                    您的浏览器不支持 audio 标签。
                  </audio>
                </div>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="讲解音频（英文）" prop="audioGuideEn">
              <div class="w-full">
                <MyUpload
                  :file-list="audioEnList"
                  :limit="1"
                  accept=".mp3"
                  @deleteFile="audioEnDeleteFile"
                  @uploadFileSuccess="audioEnSuccess"
                />
                <div v-if="audioEnList.length > 0" class="mt-2 w-[400px]">
                  <audio
                    v-for="(file, idx) in audioEnList"
                    :key="file.path || idx"
                    :src="file.path"
                    controls
                    class="w-full"
                  >
                    您的浏览器不支持 audio 标签。
                  </audio>
                </div>
              </div>
            </el-form-item>
          </el-col>
        </el-row>

        <div class="form-actions mt-6 flex justify-end">
          <el-button @click="goBack">取消</el-button>
          <el-button type="primary" @click="submitForm(formRef)">保存</el-button>
        </div>
      </el-form>
    </el-card>
    <MapSelection
      v-model="mapVisible"
      :center="{
        lng: 114.17842233364557,
        lat: 30.506250728187435
      }"
      ref="mapSelectionRef"
      @confirm="handleMapConfirm"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { Back } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import type { FormInstance } from 'element-plus'
import { useWorktabStore } from '@/store/modules/worktab'
import type { ExhibitionItemVoduixiang } from '@/api/4a/types'
import {
  scenicExhibitionItemGetUsingPost,
  scenicExhibitionItemSaveUsingPost
} from '@/api/4a/zhanpinguanli'
import MyUpload from '@/components/MyUpload/index.vue'
import MapSelection from '@/components/mapSelection/index.vue'

interface UploadResponse {
  data: {
    path: string
    name: string
    type?: string
    size?: number
  }
}

interface FileItem {
  path: string
  name: string
  type?: string
  size?: number
}

const route = useRoute()
const router = useRouter()
const formRef = ref<FormInstance>()
const exhibitionId = ref(route.query.id ? route.query.id : undefined)
const isEdit = computed(() => !!exhibitionId.value)
// 打开地图选择
const openMapSelection = () => {
  mapVisible.value = true
}

const mapVisible = ref(false)
// 表单数据
const formData = ref<Partial<ExhibitionItemVoduixiang>>({
  status: 1
})
const exhibitionStatus = ref([
  { label: '展出中', value: 1 },
  { label: '维护中', value: 2 },
  { label: '已下架', value: 3 },
])
// 表单校验规则
const rules = {
  name: [
    { required: true, message: '请输入展品名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  status: [{ required: true, message: '请选择展出状态', trigger: 'change' }],
  location: [{ required: true, message: '请输入展品定位', trigger: 'blur' }],
  floor: [{ required: true, message: '请输入展出楼层', trigger: 'blur' }],
  description: [
    { required: true, message: '请输入展品介绍', trigger: 'blur' },
    { min: 10, message: '介绍不能少于10个字符', trigger: 'blur' }
  ],
  descriptionEn: [
    { required: true, message: '请输入展品介绍（英文）', trigger: 'blur' },
    { min: 10, message: '介绍不能少于10个字符', trigger: 'blur' }
  ],
  coverImage: [{ required: false, message: '请上传封面图片', trigger: 'change' }],
  detailImages: [{ required: false, message: '请上传详情图片', trigger: 'change' }],
  audioGuide: [{ required: false, message: '请上传音频', trigger: 'change' }],
  audioGuideEn: [{ required: false, message: '请上传音频（英文）', trigger: 'change' }]
}

// 封面图片
const coverImageList = computed({
  get() {
    return JSON.parse(formData.value.coverImage || '[]')
  },
  set(value) {
    formData.value.coverImage = value
  }
})

const coverSuccess = (response: UploadResponse) => {
  coverImageList.value.push(response.data)
  coverImageList.value = JSON.stringify(coverImageList.value)
}

const coverDeleteFile = (params: FileItem) => {
  coverImageList.value = JSON.stringify(
    coverImageList.value.filter((item: FileItem) => item.path !== params.path)
  )
}

// 详情图片
const detailImageList = computed({
  get() {
    return JSON.parse(formData.value.detailImages || '[]')
  },
  set(value) {
    formData.value.detailImages = value
  }
})

const detailSuccess = (response: UploadResponse) => {
  detailImageList.value.push(response.data)
  detailImageList.value = JSON.stringify(detailImageList.value)
}

const detailDeleteFile = (params: FileItem) => {
  detailImageList.value = JSON.stringify(
    detailImageList.value.filter((item: FileItem) => item.path !== params.path)
  )
}

// 音频
const audioList = computed({
  get() {
    return JSON.parse(formData.value.audioGuide || '[]')
  },
  set(value) {
    formData.value.audioGuide = value
  }
})

const audioSuccess = (response: UploadResponse) => {
  audioList.value.push(response.data)
  audioList.value = JSON.stringify(audioList.value)
}

const audioDeleteFile = (params: FileItem) => {
  audioList.value = JSON.stringify(
    audioList.value.filter((item: FileItem) => item.path !== params.path)
  )
}

const audioEnList = computed({
  get() {
    return JSON.parse(formData.value.audioGuideEn || '[]')
  },
  set(value) {
    formData.value.audioGuideEn = value
  }
})

const audioEnSuccess = (response: UploadResponse) => {
  audioEnList.value.push(response.data)
  audioEnList.value = JSON.stringify(audioEnList.value)
}

const audioEnDeleteFile = (params: FileItem) => {
  audioEnList.value = JSON.stringify(
    audioEnList.value.filter((item: FileItem) => item.path !== params.path)
  )
}

// 获取展品详情
const getExhibitionDetail = async () => {
  try {
    if (!exhibitionId.value) return

    const res = await scenicExhibitionItemGetUsingPost({
      params: { id: exhibitionId.value }
    })
    if (res.code === 0 && res.data) {
      formData.value = res.data
    } else {
      ElMessage.error(res.msg || '获取展品详情失败')
    }
  } catch (error) {
    console.error('获取展品详情失败:', error)
    ElMessage.error('获取展品详情失败')
  }
}

// 提交表单
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return

  await formEl.validate(async (valid) => {
    if (valid) {
      try {
        const res = await scenicExhibitionItemSaveUsingPost({
          body: {
            ...formData.value,
            id: exhibitionId.value,
            descriptionEn:formData.value.descriptionEn,
            nameEn:'en'
          }
        })
        if (res.code === 0) {
          ElMessage.success(isEdit.value ? '展品信息更新成功' : '展品添加成功')
          router.push('/exhibition/ExhibitionList')
        } else {
          ElMessage.error(res.msg || '保存失败')
        }
      } catch (error) {
        console.error('保存失败:', error)
        ElMessage.error('保存失败')
      }
    }
  })
}
const handleMapConfirm = (data) => {
    // 更新位置信息
    if (data && data.point && data.surroundingPois.length > 0) {
      formData.value.location = data.surroundingPois[0].title // 保存坐标值
      formRef.value.validateField('location')
      mapVisible.value = false
    } else {
      ElMessage.error('请选择位置')
    }
  }
// 返回列表
const goBack = () => {
  const worktabStore = useWorktabStore()
  worktabStore.removeTab(route.path)
  router.push('/exhibition/ExhibitionList')
}

onMounted(() => {
  if (isEdit.value) {
    getExhibitionDetail()
  }
})
</script>

<style lang="scss" scoped>
.exhibition-edit {
  :deep(.el-upload-dragger) {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .form-section-title {
    display: flex;
    align-items: center;
    gap: 1rem;

    .form-section-line {
      flex: 1;
      height: 1px;
      background-color: var(--el-border-color);
    }
  }
}
</style> 